package com.salt.security.wechat.auth;

import com.salt.security.wechat.auth.service.WeChatPasswordLoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * 微信密码登陆身份验证器
 *
 * @author HaiBo Kuang
 * @date 2021年04月21日 上午 10:11
 */
@Component
public class WeChatPasswordAuthenticationProvider implements AuthenticationProvider {
    private final Logger logger = LoggerFactory.getLogger("WeChat_Password_Authentication_Provider");
    private WeChatPasswordLoginService loginService;

    @Autowired
    public void setPasswordAuthenticationProvider(WeChatPasswordLoginService loginService) {
        this.loginService = loginService;
    }

    /**
     * 认证主体方法
     *
     * @param authentication 认证主体信息
     * @return 结果
     * @throws AuthenticationException 认证失败异常
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.isInstanceOf(WeChatPasswordAuthenticationToken.class, authentication,
                "this object not WeChatPasswordAuthenticationToken object！！");
        logger.info("<====微信密码登录行为开始====>");
        WeChatPasswordAuthenticationToken pwdToken = (WeChatPasswordAuthenticationToken) authentication;
        String userNameOrPhone = String.valueOf(pwdToken.getPrincipal());
        String password = String.valueOf(pwdToken.getCredentials());
        String openId = pwdToken.getOpenId();
        Long userId = loginService.login(userNameOrPhone, password);
        logger.info("<==当前登录成功的微信用户id：[{}]==>", userId);
        logger.info("<==开始绑定用户微信openId关系==>");
        // 做绑定
//        bindService.bind
        return authentication;
    }

    /**
     * 对验证主体PasswordAuthenticationToken提供支持
     *
     * @param authentication 认证
     * @return 是否支持
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return WeChatPasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
